package com.zx.jhpt.login;

import com.zx.framework.core.util.*;
import com.zx.framework.core.util.gson.GsonUtil;
import com.zx.framework.plat.dept.po.Dept;
import com.zx.framework.plat.login.LoginAdapterController;
import com.zx.framework.plat.user.vo.UserVo;
import com.zx.framework.web.exception.UIException;
import com.zx.jhpt.excel.Engine;
import com.zx.jhpt.excel.vo.Risk;
import com.zx.jhpt.po.Enclosure;
import com.zx.jhpt.po.Fxfkjz;
import com.zx.jhpt.service.EnclosureService;
import com.zx.jhpt.service.EngineService;
import com.zx.jhpt.service.FxfkjzService;
import com.zx.jhpt.service.ReplyMessageService;
import org.apache.commons.io.FilenameUtils;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping("/encl")
public class EnclosureController extends LoginAdapterController {

    private static final Logger LOGGER = Logger.getLogger(EnclosureController.class);

    //市移动管理员附件信息标识 值
    private static final String PKID = "HB.SJ.UPLOAD";

    @Resource
    private EnclosureService enclosureService;
    @Resource
    private ReplyMessageService replyMessageService;
    @Resource
    private FxfkjzService fxfkjzService;
    @Resource
    private EngineService engineService;

    @Resource
    private String jhptUpload;

    @RequestMapping("/openUpload")
    public String analysis(Model model) {
        List<Fxfkjz> fxLst = fxfkjzService.getAll();
        model.addAttribute("fxLst", fxLst);
        return "upload";
    }

    /**
     * 核查文件上传
     *
     * @param multipartHttpServletRequest
     * @param hcsj                        核查日期
     * @param fileId                      文件ID为风险ID
     * @return
     */
    @RequestMapping(value = "/uploadSJ", method = RequestMethod.POST)
    @ResponseBody
    public Map<String, Object> uploadSJ(
            MultipartHttpServletRequest multipartHttpServletRequest,
            String hcsj,
            @RequestParam(required = false) String fileId
    ) {
        if (StringUtil.isEmpty(hcsj)) {
            return clientMap().failure().message("请选择文件日期！").getMap();
        }
        MultipartFile mufile = multipartHttpServletRequest.getFile("uploadFile");
        if (mufile == null || mufile.getSize() == 0) {
            return clientMap().failure().message("请选择上传文件！").getMap();
        }
        UserVo loginUser = getLoginUser();
        List<Dept> depts = loginUser.getDepts();
        List<String> deptIds = new ArrayList<>();
        for (Dept dept : depts) {
            deptIds.add(dept.getId());
        }
        //查看上传权限
        if (!deptIds.contains("HB.SJ.YZ")) {
            return clientMap().failure().message("无权上传核查文件！").getMap();
        }
        try {
            String fileOrgName = mufile.getOriginalFilename();
            String fileExtension = FilenameUtils.getExtension(fileOrgName).toLowerCase();
            String tmpPath = jhptUpload + "temp" + File.separator + RandomUtil.getCurrentDateSequen();
            File tmpPathF = new File(tmpPath);
            LOGGER.debug("make temp dir success:" + tmpPathF.mkdirs());
            String tmpFileStr = tmpPath + File.separator + mufile.getOriginalFilename();
            File tmpFile = new File(tmpFileStr);
            mufile.transferTo(tmpFile);
            if (StringUtil.isEmpty(fileId) && "7z,rar,zip".contains(fileExtension)) {
                // 如果传的是压缩包,解压并把每个文件处理
                FileUtil.extract(tmpFileStr);
                Collection<File> files = FileUtil.listFiles(tmpPathF, new String[]{"xlsx"}, true);
                for (File f : files) {
                    try {
                        exeFXFile(f, hcsj);
                    } catch (Exception e) {
                        LOGGER.error(e);
                    }
                }
            } else {
                // 如果传的不是压缩包,直接处理
                exeFXFile(tmpFile, hcsj);
            }
            return clientMap().success().message("上传成功！").getMap();
        } catch (Exception e) {
            return clientMap().failure().message(e.getMessage()).getMap();
        }
    }

    private void exeFXFile(File file, String cycle) {
        String baseName = FilenameUtils.getBaseName(file.getName());
        String fxid = baseName.split("_")[0];
        Risk risk = Engine.getRisk(fxid);
        List<Object[]> datas = Engine.getData(risk, file.getAbsolutePath());
        engineService.saveDatas(risk, datas, cycle);
    }

    /**
     * 回执上传
     *
     * @param multipartHttpServletRequest
     * @param hcsj                        核查日期
     * @return
     */
    @RequestMapping(value = "/uploadHZ", method = RequestMethod.POST)
    @ResponseBody
    public void uploadHZ(HttpServletResponse response, MultipartHttpServletRequest multipartHttpServletRequest, String rpid, String hcsj) {
        response.setContentType("text/plain;charset=UTF-8");
        try {
            if (StringUtil.isEmpty(hcsj)) {
                response.getWriter().write(GsonUtil.object2Json(clientMap().failure().message("请选择文件日期！").getMap()));
                return;
            }
            MultipartFile mufile = multipartHttpServletRequest.getFile("uploadFile");
            if (mufile == null || mufile.getSize() == 0) {
                response.getWriter().write(GsonUtil.object2Json(clientMap().failure().message("请选择上传文件！").getMap()));
                return;
            }

            UserVo loginUser = getLoginUser();
            enclosureService.saveHZ(mufile, jhptUpload, hcsj, rpid, loginUser);
            response.getWriter().write(GsonUtil.object2Json(clientMap().success().message("上传成功！").getMap()));
        } catch (Exception e) {
            try {
                response.getWriter().write(GsonUtil.object2Json(clientMap().failure().message(e.getMessage()).getMap()));
            } catch (IOException e1) {
                e1.printStackTrace();
            }
        }
    }

    @RequestMapping(value = "/download")
    @ResponseBody
    public void download(String id, HttpServletResponse response) {
        Enclosure enclosure = enclosureService.findById(id);
        OutputStream stream = null;
        try {
            String disPath = jhptUpload + enclosure.getUrl() + File.separator + enclosure.getPkid() + ".enc";
            byte[] bytes = FileUtil.readFileToByteArray(new File(disPath));

            response.setContentType("application/x-msdownload");
            response.setHeader("Content-Disposition", "attachment; filename=" + (new String(enclosure.getFilename().getBytes("gb2312"), "iso8859-1")));
            stream = response.getOutputStream();
            stream.write(bytes);
            response.flushBuffer();
        } catch (Exception e) {
            throw new UIException("风险文件获取失败！", e);
        } finally {
            try {
                if (null != stream) {
                    stream.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    public static void main(String[] args) {
        System.out.println(SecurityUtil.decryptAES("W_WikXm5c-cX4c7F4W8nJg"));
    }
}
